import re

from django import forms


class UserProfileForm(forms.Form):
    name = forms.CharField(required=True, max_length=10, min_length=2,
                           error_messages={
                               'required': '请填写用户名',
                               'max_length': '用户名长度不多于10个字符',
                               'min_length': '用户名长度不少于2个字符'
                           })
    avatar = forms.ImageField(required=False)


class AuthForm(forms.Form):
    real_name = forms.CharField(required=True, max_length=10, min_length=2,
                                error_messages={
                                   'required': '请填写姓名',
                                   'max_length': '请输入正确的姓名',
                                   'min_length': '请输入正确的姓名'
                                })
    id_card = forms.CharField(required=True,
                              error_messages={
                                  'required': '请输入身份证号',
                              })

    def clean(self):
        if len(self.data.get('id_card')) == 0:
            return None
        # id_card如果不满足长度等于18，到clean这一步的时候，id_card的值为空，拿一个空去做正则匹配会报错
        if len(self.data.get('id_card')) != 18:
            raise forms.ValidationError({'id_card': '请输入正确的身份证号'})
        IDCard = r'^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$'
        result = re.fullmatch(IDCard, self.cleaned_data.get('id_card'))
        if not result:
            raise forms.ValidationError({'id_card': '身份证号码有误，请重新输入'})
        # 如果身份证号码没错，这里要匹配公安局数据库？
        return self.cleaned_data


class NewHouseForm(forms.Form):
    title = forms.CharField(required=True, max_length=64,
                            error_messages={
                                'max_length': '标题最长不超过64个字符'
                            })
    price = forms.IntegerField()
    address = forms.CharField(max_length=512,
                              error_messages={
                                  'max_length': '地址最长不超过512个字符'
                              })
    room_count = forms.IntegerField()
    acreage = forms.IntegerField()
    unit = forms.CharField(max_length=32,
                           error_messages={
                               'max_length': '描述最长不超过32个字符'
                           })
    capacity = forms.IntegerField()
    beds = forms.CharField(max_length=64,
                           error_messages={
                               'max_length': '字符最长不超过64个字符'
                           })
    deposit = forms.IntegerField()
    min_days = forms.IntegerField()
    max_days = forms.IntegerField()
    area_id = forms.CharField()
    house_image = forms.ImageField(required=True)











